package pl.streamsoft.currencyApp.GUI.services;

import java.math.BigDecimal;
import java.util.List;

import pl.streamsoft.currencyApp.model.Country;
import pl.streamsoft.currencyApp.model.Currency;
import pl.streamsoft.currencyApp.services.ICountryService;
import pl.streamsoft.currencyApp.services.ICurrencyService;

public class AppService implements IAppService {

	private ICountryService countryService;
	private ICurrencyService currencyService;
	
	public AppService(ICountryService countryService, ICurrencyService currencyService){
		this.countryService = countryService;
		this.currencyService = currencyService;
	}
	
	public boolean addCountry(String name) {
		if(checkIfCountryExist(name)){
			return false;
		}
		else{
			Country country = new Country();
			country.setName(name);
			countryService.getListOfCountries().add(country);
			return true;
		}
	}

	public boolean addNewCurrencyToCountry(String countryName, String name,
			String currencyCode, int converter, String averageRate) {
		if(averageRate.contains(",")){
			averageRate.replace(",", ".");
		}
		
		if(checkIfCountryExist(countryName)){
			return false;
		}
		else{
			Currency currency = new Currency();
			currency.setName(name);
			currency.setCurrencyCode(currencyCode);
			currency.setConverter(converter);
			currency.setAverageRate(new BigDecimal(averageRate));
			
			countryService.getCountryByName(countryName).getCurrencyList().add(currency);
			return true;
		}
	}

	public String showAllCurrenciesOfCountry(String nameOfCountry) {
		if(checkIfCountryExist(nameOfCountry)){
			List<Currency> listOfCurrencies = countryService.getCountryByName(nameOfCountry).getCurrencyList();
			String result = "";
			for(Currency el: listOfCurrencies){
				result += "Currency name: "+ el.getName() + ", code: "+el.getCurrencyCode()+", converter: "+el.getConverter()+", average rate: "+ el.getAverageRate()+"\n";
			}
			return result;
		}
		return "";
	}

	public String showAllCurrentCurrencies() {
		List<Currency> listOfCurrencies = currencyService.getListOfCurrencies();
		String result = "";
		for(Currency el: listOfCurrencies){
			result += "Currency name: "+ el.getName() + ", code: "+el.getCurrencyCode()+", converter: "+el.getConverter()+", average rate: "+ el.getAverageRate()+"\n";
		}
		return result;
	}

	public boolean addExistingCurrencyToCountry(String currencyCode,
			String countryName) {
		Currency currency = currencyService.getCurrencyByCode(currencyCode);
		if(currency==null){
			return false;
		}
		for(Country el: countryService.getListOfCountries()){
			if(el.getName().equals(countryName)){
				el.getCurrencyList().add(currency);
				return true;
			}
		}
		return false;
	}
	
	public boolean checkIfCountryExist(String name){
		for(Country el: countryService.getListOfCountries()){
			if(el.getName().equals(name)){
				return true;
			}
		}
		return false;
	}

}
